package h0827;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
  * @description 二叉树的层序遍历
  * @author 不知名帅哥
  * @date 2024/8/27 22:17
  * @version 1.0
*/
public class BFSBinaryTree {
    public static void main(String[] args) {
        TreeNode root=new TreeNode(3);
        root.left=new TreeNode(9);
        root.right=new TreeNode(20,new TreeNode(15),new TreeNode(7));
        System.out.println(levelOrder(root));
    }

    public static List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res=new ArrayList<>();

        LinkedList<TreeNode> queue=new LinkedList<>(); //使用队列
        queue.add(root);
        while (!queue.isEmpty()){
            int size = queue.size();
            List<Integer> temp=new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode curNode = queue.removeFirst();
                temp.add(curNode.val);
                if (curNode.left!=null){
                    queue.addLast(curNode.left);
                }
                if (curNode.right!=null){
                    queue.addLast(curNode.right);
                }
            }
            res.add(temp);
        }
        return res;
    }
     static class TreeNode {
         int val;
         TreeNode left;
         TreeNode right;

         TreeNode() {
         }

         TreeNode(int val) {
             this.val = val;
         }

         TreeNode(int val, TreeNode left, TreeNode right) {
             this.val = val;
             this.left = left;
             this.right = right;
         }
     }

}
